package com.sailfish.springbootdemo.controller.db2;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.PcbCapacityApproveDetail;
import com.sailfish.springbootdemo.pojo.db2.PcbCapacityParam;
import com.sailfish.springbootdemo.pojo.db2.PcbCapacityParamHistory;
import com.sailfish.springbootdemo.pojo.db2.PcbCapacityParamVersion;
import com.sailfish.springbootdemo.service.db2.PcbCapacityParamService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/pcbCapacityParam")
public class PcbCapacityParamController {

    @Autowired
    private PcbCapacityParamService pcbCapacityParamService;


    @PostMapping("/getAll")
    public Result getType(Integer id, String paramname, String version, Integer status, Integer versionType) {
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        }
        if (versionType == null) {
            return ResultUtil.error(500, "参数versionType是空的", "param versionType is null", null);
        }
        if (versionType == 2) {
            final PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 2);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityParam> children = pcbCapacityParamService.getChildrenById(id, paramname, status);
                    return ResultUtil.success(children);
                } else {
                    List<PcbCapacityParamHistory> childrenByIdHistory = pcbCapacityParamService.getChildrenByIdHistory(id, version);
                    if (childrenByIdHistory == null || childrenByIdHistory.size() == 0) {
                        return ResultUtil.error(500, "没有该年份模版", "", null);
                    } else {
                        return ResultUtil.success(childrenByIdHistory);
                    }
                }
            } else {
                List<PcbCapacityParam> children = pcbCapacityParamService.getChildrenById(id, paramname, status);
                return ResultUtil.success(children);
            }
        } else {
            final PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityParam> children = pcbCapacityParamService.getChildrenById(id, paramname, status);
                    return ResultUtil.success(children);
                } else {
                    List<PcbCapacityParamHistory> childrenByIdHistory = pcbCapacityParamService.getChildrenByIdHistory(id, version);
                    if (childrenByIdHistory == null || childrenByIdHistory.size() == 0) {
                        return ResultUtil.error(500, "没有该年份模版", "", null);
                    } else {
                        return ResultUtil.success(childrenByIdHistory);
                    }
                }
            } else {
                List<PcbCapacityParam> children = pcbCapacityParamService.getChildrenById(id, paramname, status);
                return ResultUtil.success(children);
            }
        }
    }

    @PostMapping("/getParamList")
    public Result getParamList(Integer id1, Integer id2, Integer id3, Integer level, String searchK, String searchV, String version) {
        final PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 2);
        if (newestVersion != null) {
            String str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
            if (version.equals(str_newestVersion)) {
                Result paramList = pcbCapacityParamService.getParamList(id1, id2, id3, level, searchK, searchV);
                return paramList;
            }
        }
        Result paramListHistory = pcbCapacityParamService.getParamListHistory(id1, id2, id3, level, searchK, searchV, version);
        return paramListHistory;
    }

    @PostMapping("/delete")
    public Result deleteById(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        return pcbCapacityParamService.delete(id);
    }

    @PostMapping("/insertOrUpdate")
    public Result insertOrUpdate(@RequestBody String data) {
        return pcbCapacityParamService.insertOrUpdate(data);
    }

    @PostMapping("/outputParamTemplate")
    public Result outputParamTemplate(String version) throws IOException {

        Result result = pcbCapacityParamService.outputParamTemplate(version);
        if (result.getCode().equals(200)) {
            try {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fname = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                Map<String, Object> map = new HashMap<>();
                map.put("base64", base64);
                map.put("fileName", fname);
                return ResultUtil.success(map);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } else {
            return result;
        }
    }

    //保存历史版本数据
    @PostMapping("/saveOldParamTemplate")
    public Result saveOldParamTemplate(String versionYear, String versionNum) {
        return pcbCapacityParamService.saveOldParamTemplate2(versionYear, versionNum);
    }

    //保存历史版本数据
    @PostMapping("/saveParamTemplate")
    public Result saveParamTemplate(String versionYear, String versionNum) {
        return pcbCapacityParamService.saveTemplate(versionYear, versionNum);
    }

    @PostMapping("/getVersionList")
    public Result getVersionList(String versionYear, Integer versionType) {
        List<PcbCapacityParamVersion> versionList = pcbCapacityParamService.getVersionListByTemplateStatus(versionYear, versionType);
        return ResultUtil.success(versionList);
    }

    //versionType 1数据 2模板
    @PostMapping("/getNewestVersion")
    public Result getNewestVersion(String versionYear, Integer versionType) {
        if (versionType == null) {
            return ResultUtil.error(500, "参数versionType为空", "param versionType is null", null);
        }
        PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersionByTemplateStatus(versionYear, versionType);
        return ResultUtil.success(newestVersion);
    }

    @PostMapping("/checkOldParamTemplate")
    public Result checkOldParamTemplate(String versionYear, String versionNum, Integer versionType) {
        return pcbCapacityParamService.checkOldParamTemplate(versionYear, versionNum, versionType);
    }

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;

    @Value("${personal.config.file.pcb-param-template}")
    private String pcbParamTemplateUrl;

    @PostMapping("/downloadTemplate")
    public Result downloadTemplate() {
        try {
            String filepath = pcbParamTemplateUrl;
            File file = new File(filepath);
            String fname = file.getName();
            byte[] bytedata = null;
            InputStream in = new FileInputStream(file);
            bytedata = new byte[in.available()];
            in.read(bytedata);
            in.close();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(bytedata);

            Map<String, Object> map = new HashMap<>();
            map.put("base64", base64);
            map.put("fileName", fname);
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //追加导入
    @PostMapping("/importParamTemplate")
    public Result importParamTemplate(HttpServletRequest req) throws IOException {

        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
        MultipartFile file = mRequest.getFile("file");
        String type = mRequest.getParameter("type");//type==0给出弹框，type=1直接导入
        if (type == null) {
            return ResultUtil.error(500, "参数type为空", "param type is null", null);
        }
        Result result = pcbCapacityParamService.importParamTemplate(file, type);
        return result;
    }

    //覆盖导入
    @PostMapping("/importParamTemplate2")
    public Result importParamTemplate2(HttpServletRequest req) throws IOException {

        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
        MultipartFile file = mRequest.getFile("file");
        String type = mRequest.getParameter("type");//type==0给出弹框，type=1直接导入
        if (type == null) {
            return ResultUtil.error(500, "参数type为空", "param type is null", null);
        }
        Result result = pcbCapacityParamService.importParamTemplate2(file, type);
        return result;
    }

    /*
    模板分发
     */
    @PostMapping("/publishTemplate")
    public Result publishTemplate() {
        return pcbCapacityParamService.publishTemplate();
    }

    /*一键必填、非必填*/
    @PostMapping("/updateRequire")
    public Result updateRequire(Integer isRequire) {
        return pcbCapacityParamService.updateRequire(isRequire);
    }

    @PostMapping("/checkHasNotApproved")
    //判断是否有审核未通过的
    public Result checkHasNotApproved() {
        return pcbCapacityParamService.checkHasNotApproved();
    }
}
